<?php
namespace App\Jobs;

use DB;
use App\Jobs\Job;

use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendEmail extends Job implements SelfHandling, ShouldQueue
{
	protected $id;
	protected $from;
	protected $to;
	protected $tpl_name;
	protected $subject;
    protected $sub;
    /**
     * Create a new job instance.
     *
     * @param  User  $user
     * @return void
     */
    public function __construct($data)
    {
    	$this->id      = $data["id"];
        $this->from    = $data["from"];
    	$this->to      = $data["to"];
        $this->tpl_name= $data["tpl_name"];
        $this->subject = $data["subject"];
        $this->sub     = $data["sub"];
    }

    /**
     * Execute the job.
     *
     * @param  Mailer  $mailer
     * @return void
     */
    public function handle()
    {
        $url  = "http://api.sendcloud.net/apiv2/mail/sendtemplate";
        $data = [
            "apiUser"   => "ptimeinform",
            "apiKey"    => "lqsy1ixNOyFkN74k",
            "from"      => "拾光通知服务<service@timepicker.cn>",
            "subject"   => $this->subject,
            "templateInvokeName" => $this->tpl_name,
            "xsmtpapi"  => json_encode([
                    "to"    => $this->to,
                    "sub"   => $this->sub
            ])
        ];
        //发送
        $sendTime = date("Y-m-d H:i:s");
        try{
            $result = $this->curl_post($url, http_build_query($data));
            $result = ["send_code"=>"1","send_time"=>$sendTime,"send_detail"=>$result];
        }catch(Exception $e){
            $result = ["send_code"=>"-1","send_time"=>$sendTime,"send_detail"=>json_encode($e)];
        }

        DB::table("im_inform_user_method")->where("id",$this->id)->update($result);
        return true; 
    }

    /**
     * PHP CURL 模块发送post请求
     * 
     * @param uri     请求地址
     * @param data    所需发送的数据
     * @return 
     */
    private function curl_post( $uri , $data ){
        $temp_uri = $uri;
        $temp_data = $data;
        $ch = curl_init();
        curl_setopt ( $ch, CURLOPT_URL, $temp_uri );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, array("Expect:") );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $temp_data );
        $temp_post_result = curl_exec ( $ch );
        curl_close ( $ch );
        return $temp_post_result;
    }

}